<template>
    <van-list :immediate-check="false" error-text="加载失败 请点击重试" v-model:loading="loading" :finished="finished" finished-text="没有更多了"
        @load="onLoad">
        <comment-item
        @upCommentLiking="item.is_liking = !item.is_liking"
        @upCommentPraise="$event===1?item.like_count--:item.like_count++"
        @reply-click="$emit('reply-click',$event)"
        v-for="(item, index) in list"
        :comment="item" :key="index" />
    </van-list>
</template>

<script>
import { getCommentAPI } from '@/api/comment'
import commentItem from './commentItem.vue'
import { ref } from 'vue'
export default {
  name: 'commentList',
  props: {
    source: {
      type: [Number, String, Object],
      required: true
    },
    list: {
      type: Array,
      default: () => []
    },
    type: {
      type: String,
      // 自定义props数据验证 返回Boolean，为true通过 为fasle不通过
      validator (value) {
        return ['a', 'c'].includes(value)
      },
      default: 'a'
    }
  },
  components: {
    commentItem
  },
  setup (props, content) {
    const loading = ref(false)
    const finished = ref(false)
    const offset = ref(null)
    const onLoad = async () => {
      try {
        const { data } = await getCommentAPI({
          type: props.type,
          source: props.source,
          offset: offset.value,
          limit: 10
        })
        const { results } = data.data
        if (results[0] != null) {
          // 评论数量传递给父组件 整个评论数据
          content.emit('onload-success', data.data)
        }
        loading.value = false
        if (results.length === 10) {
          offset.value = data.data.last_id
        } else {
          finished.value = true
        }
      } catch (err) {
        console.log(err)
        loading.value = false
        finished.value = true
      }
    }
    onLoad()
    return {
      onLoad,
      loading,
      finished
    }
  }

}
</script>

<style scoped lang="less">

</style>
